package org.gd.jms.actimemq;

import com.google.common.base.Objects;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.util.concurrent.atomic.AtomicInteger;

public class HelloWorldConsumer implements Runnable, ExceptionListener {

    public void run() {
        Connection connection = null;
        Session session = null;
        MessageConsumer consumer = null;
        try {
            // Create a ConnectionFactory
            ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

            // Create a Connection
            connection = connectionFactory.createConnection();
            connection.start();

            connection.setExceptionListener(this);

            // Create a Session
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            // Create the destination (Topic or Queue)
            Destination destination = session.createQueue("TEST.FOO");

            // Create a MessageConsumer from the Session to the Topic or Queue
            consumer = session.createConsumer(destination);

            AtomicInteger count = new AtomicInteger(0);
            while(Objects.equal(Boolean.FALSE, Boolean.FALSE)) {
                if(count.addAndGet(1) > 10) {
                    break;
                }
                // Wait for a message
                Message message = consumer.receive(2000);

                if (message instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage) message;
                    String text = textMessage.getText();
                    System.out.println("Received text: " + text);
                } else {
                    System.out.println("Received message: " + message);
                }
            }
        } catch (Exception e) {
            System.out.println("Caught: " + e);
            e.printStackTrace(System.err);
        } finally {
            if(consumer != null) {
                try {
                    consumer.close();
                } catch (JMSException e) {
                    e.printStackTrace(System.err);
                }
            }
            if(session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    e.printStackTrace(System.err);
                }
            }
            if(connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace(System.err);
                }
            }
        }
    }

    public synchronized void onException(JMSException ex) {
        System.out.println("JMS Exception occured.  Shutting down client.");
    }
}
